package com.licerlee.sheboot.common.service;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import com.licerlee.sheboot.common.dao.CommonDao;
import com.licerlee.sheboot.common.domain.BaseEntity;

// 通过组合方式持有 dao对象引用
// 只提供公共访问能力
public abstract class AbstractCommonService<E extends BaseEntity, ID extends Serializable> {

	private static final String ID_MUST_BE_NOT_NULL = "主键不能为空";
	
	protected CommonDao<E, ID> commonDao;

	public CommonDao<E, ID> getCommonDao() {
		return commonDao;
	}
	// 注入commonDao接口实现
	public void setCommonDao(CommonDao<E, ID> commonDao) {
		this.commonDao = commonDao;
	}

	
	public E get(ID id) {
		Assert.notNull(id, ID_MUST_BE_NOT_NULL);
		return commonDao.getOne(id);
	}

	public E find(ID id) {
		Assert.notNull(id, ID_MUST_BE_NOT_NULL);
		return commonDao.findOne(id);
	}

	public List<E> findAll() {
		return commonDao.findAll();
	}

	public void save(E e) {
		commonDao.save(e);
	}
	
	public void save(E e, ID id) {
		E e1 = null;
		if(!ObjectUtils.isEmpty(id)){
			e1 = commonDao.findOne(id);
			BeanUtils.copyProperties(e, e1);
		}else{
			e1 = e;
		}
		commonDao.save(e1);
	}

	/**
	 * 根绝主键逻辑删除
	 * @param id
	 */
	public void delete(ID id) {
		Assert.notNull(id, ID_MUST_BE_NOT_NULL);
		E e = commonDao.findOne(id);
		e.setDeleteFlag(e.DELETE_FLAG_DELETED);;
		commonDao.save(e);
	}
	

	public long count() {
		return commonDao.count();
	}
}
